<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span><el-icon><User /></el-icon> 个人信息</span>
          <el-button type="primary" @click="showEditDialog('info')">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
        </div>
      </template>
      <div class="profile-content">
        <div class="avatar-section">
          <el-avatar :size="100" :src="currentAvatar" />
          <div class="avatar-actions">
            <el-button type="primary" @click="handleAvatarClick">
              <el-icon><Upload /></el-icon> 更换头像
            </el-button>
            <input
              ref="avatarInput"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleAvatarChange"
            />
          </div>
        </div>
        <div class="info-section">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户名">
              <el-icon><User /></el-icon>
              {{ userInfo.username }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              <el-icon><Phone /></el-icon>
              {{ userInfo.phone || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
                {{ userInfo.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(userInfo.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(userInfo.updateTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <ProfileAddress ref="profileAddressRef" />

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span><el-icon><Lock /></el-icon> 修改密码</span>
          <el-button type="primary" @click="showEditDialog('password')">
            <el-icon><Edit /></el-icon> 修改
          </el-button>
        </div>
      </template>
      <div class="password-tip">
        <el-icon><InfoFilled /></el-icon>
        <span>定期修改密码可以提高账号安全性</span>
      </div>
    </el-card>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="editInfoDialogVisible"
      title="编辑个人信息"
      width="500px"
    >
      <el-form :model="editInfoForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editInfoForm.username" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editInfoForm.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editInfoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveInfo">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="editPasswordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form :model="editPasswordForm" label-width="100px" :rules="passwordRules">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="editPasswordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="editPasswordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="editPasswordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePassword">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Phone, Money, Calendar, Upload, Edit, Lock, InfoFilled } from '@element-plus/icons-vue'
import type { ProfileInfo } from '@/api/profile'
import { getProfileInfo, updateProfile, updatePassword } from '@/api/profile'
import { getUserImage, uploadAvatar } from '@/api/image'
import type { GeneratedImage } from '@/api/image'
import ProfileAddress from './components/ProfileAddress.vue'
import { format } from 'date-fns'
import type { ApiResponse } from '@/types/api'

interface ImageResponse {
  id: number
  userId: number
  seed: number
  truncationPsi: number
  imageUrl: string
  ossPath: string
  createTime: string
  updateTime: string
}

interface AddressInfo {
  receiver: string
  phone: string
  address: string
}

interface EditInfoForm {
  username: string
  phone: string
}

interface EditAddressForm {
  receiver: string
  phone: string
  address: string
}

interface EditPasswordForm {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

const userInfo = ref<ProfileInfo>({
  id: '',
  username: '',
  phone: '',
  balance: 0,
  status: 0,
  createTime: '',
  updateTime: ''
})

const currentAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
const avatarInput = ref<HTMLInputElement | null>(null)
const addressInfo = ref<AddressInfo | null>(null)
const profileAddressRef = ref()

// 对话框控制
const editInfoDialogVisible = ref(false)
const editPasswordDialogVisible = ref(false)

// 表单数据
const editInfoForm = ref<EditInfoForm>({
  username: '',
  phone: ''
})

const editAddressForm = ref<EditAddressForm>({
  receiver: '',
  phone: '',
  address: ''
})

const editPasswordForm = ref<EditPasswordForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== editPasswordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const formatDate = (date: string) => {
  if (!date) return '未设置'
  return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
}

const fetchUserInfo = async () => {
  try {
    const response = (await getProfileInfo()) as unknown as ApiResponse<ProfileInfo>
    console.log('用户信息响应:', response)

    if (response.code === 200 && response.data) {
      userInfo.value = response.data
      console.log('更新后的用户信息:', userInfo.value)

      const userId = Number(response.data.id)
      if (isNaN(userId)) {
        console.warn('用户ID无效，跳过头像获取')
        currentAvatar.value = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      } else {
        try {
          const imageResponse = (await getUserImage(userId)) as unknown as ApiResponse<GeneratedImage>
          console.log('头像响应:', imageResponse)
          if (imageResponse.code === 200 && imageResponse.data) {
            currentAvatar.value = imageResponse.data.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
          } else {
            console.warn('获取头像失败，使用默认头像')
            currentAvatar.value = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
          }
        } catch (imageError) {
          console.error('获取头像失败:', imageError)
          currentAvatar.value = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
        }
      }
    } else {
      console.error('获取用户信息失败:', response)
      throw new Error(response.msg || '获取用户信息失败')
    }
  } catch (error: any) {
    console.error('获取用户信息失败，详细错误:', error)
    ElMessage.error(error.message || '获取用户信息失败')
  }
}

const showEditDialog = (type: 'info' | 'password') => {
  switch (type) {
    case 'info':
      editInfoForm.value = {
        username: userInfo.value.username,
        phone: userInfo.value.phone || ''
      }
      editInfoDialogVisible.value = true
      break
    case 'password':
      editPasswordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      editPasswordDialogVisible.value = true
      break
  }
}

const saveInfo = async () => {
  try {
    const response = await updateProfile({
      username: editInfoForm.value.username,
      phone: editInfoForm.value.phone
    })
    if (response.data.code === 200) {
      ElMessage.success('个人信息更新成功')
      editInfoDialogVisible.value = false
      await fetchUserInfo()
    } else {
      ElMessage.error(response.data.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const savePassword = async () => {
  try {
    const response = await updatePassword(
      editPasswordForm.value.oldPassword,
      editPasswordForm.value.newPassword
    )
    if (response.data.code === 200) {
      ElMessage.success('密码修改成功')
      editPasswordDialogVisible.value = false
    } else {
      ElMessage.error(response.data.msg || '修改失败')
    }
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

const handleAvatarClick = () => {
  avatarInput.value?.click()
}

const handleAvatarChange = async (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    try {
      const response = await uploadAvatar(file)
      if (response.code === 200 && response.data) {
        ElMessage.success('头像上传成功')
        currentAvatar.value = response.data.imageUrl
      } else {
        ElMessage.error(response.msg || '头像上传失败')
      }
    } catch (error) {
      console.error('上传失败:', error)
      ElMessage.error('上传失败')
    }
  }
}

onMounted(() => {
  fetchUserInfo()
})

onUnmounted(() => {
  // 清理工作
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card,
.password-card {
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.profile-content {
  display: flex;
  gap: 40px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.avatar-actions {
  display: flex;
  gap: 10px;
}

.info-section {
  flex: 1;
}

.password-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;
}

:deep(.el-descriptions__label) {
  width: 100px;
}

:deep(.el-descriptions__content) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-avatar) {
  width: 128px !important;
  height: 128px !important;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-avatar img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
